/**
 * @author Eberhard Graether / http://egraether.com/
 * @author Mark Lundin 	/ http://mark-lundin.com
 * @author Simone Manini / http://daron1337.github.io
 * @author Luca Antiga 	/ http://lantiga.github.io
 */

import {
    EventDispatcher,
    MOUSE,
    Quaternion,
    Vector2,
    Vector3
} from "./three.module.js";

var TrackballControls = function ( object, domElement ) {

    var _this = this;
    //0是左键，1是中键，2是右键
    var STATE = { NONE: -1, SELECTION: 0, ROTATE: 1, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 };

    this.object = object;
    this.domElement = ( domElement !== undefined ) ? domElement : document;

    // API

    this.enabled = true;

    this.screen = { left: 0, top: 0, width: 0, height: 0 };

    //这里也就设置了默认值，在调用这个类的时候，有重新修改这些参数中的部分
    this.rotateSpeed = 1.0;
    this.zoomSpeed = 1.2;
    this.panSpeed = 0.3;

    this.noRotate = false;
    this.noZoom = false;
    this.noPan = false;
    this.noSelection = false;

    this.staticMoving = false;
    this.dynamicDampingFactor = 0.2;

    this.minDistance = 0;
    this.maxDistance = Infinity;

    this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];

    //这里设定的中键按下是旋转，中间的缩放，右键是平移
    this.mouseButtons = {LEFT:STATE.SELECTION ,MIDDLE_DOWN: STATE.ROTATE, MIDDLE: STATE.ZOOM, RIGHT: STATE.PAN };

    // internals  内部的？

    //这个设置的是显示在屏幕中的方块
    this.target = new Vector3();

    var EPS = 0.000001;

    var lastPosition = new Vector3();

    var _state = STATE.NONE,
        _keyState = STATE.NONE,

        _eye = new Vector3(),

        _movePrev = new Vector2(),
        _moveCurr = new Vector2(),

        _lastAxis = new Vector3(),
        _lastAngle = 0,

        _zoomStart = new Vector2(),
        _zoomEnd = new Vector2(),

        _touchZoomDistanceStart = 0,
        _touchZoomDistanceEnd = 0,

        _panStart = new Vector2(),
        _panEnd = new Vector2();

    // for reset

    this.target0 = this.target.clone();
    this.position0 = this.object.position.clone();
    this.up0 = this.object.up.clone();

    //设置两个时间，用于记录鼠标右键按下和松起相差的时间,这两个事件初始化为0
    var start_time=0;
    var end_time=0;

    // events

    var changeEvent = { type: 'change' };
    var startEvent = { type: 'start' };
    var endEvent = { type: 'end' };


    //为左键框选框设置一些参数
    var pageX = null;                   //记录鼠标左键点击下去时候的横坐标
    var pageY = null;                   //记录鼠标左键点击下去时候的纵坐标
    var obj = document.body;
    var button_left_isDown = false;


    // methods

    function $(select){
        //相当于函数$(id=select)=document.query.Selector(id=select),获取文档中id=select的元素
        return document.querySelector(select)
    }


    this.handleResize = function () {

        if ( this.domElement === document ) {

            this.screen.left = 0;
            this.screen.top = 0;
            this.screen.width = window.innerWidth;
            this.screen.height = window.innerHeight;

        } else {

            var box = this.domElement.getBoundingClientRect();
            // adjustments come from similar code in the jquery offset() function
            var d = this.domElement.ownerDocument.documentElement;
            this.screen.left = box.left + window.pageXOffset - d.clientLeft;
            this.screen.top = box.top + window.pageYOffset - d.clientTop;
            this.screen.width = box.width;
            this.screen.height = box.height;
        }

    };

    var getMouseOnScreen = ( function () {

        var vector = new Vector2();

        return function getMouseOnScreen( pageX, pageY ) {

            vector.set(
                ( pageX - _this.screen.left ) / _this.screen.width,
                ( pageY - _this.screen.top ) / _this.screen.height
            );

            return vector;

        };

    }() );

    var getMouseOnCircle = ( function () {

        var vector = new Vector2();

        return function getMouseOnCircle( pageX, pageY ) {

            vector.set(
                ( ( pageX - _this.screen.width * 0.5 - _this.screen.left ) / ( _this.screen.width * 0.5 ) ),
                ( ( _this.screen.height + 2 * ( _this.screen.top - pageY ) ) / _this.screen.width ) // screen.width intentional
            );

            return vector;

        };

    }() );

    this.rotateCamera = ( function () {

        var axis = new Vector3(),
            quaternion = new Quaternion(),
            eyeDirection = new Vector3(),
            objectUpDirection = new Vector3(),
            objectSidewaysDirection = new Vector3(),
            moveDirection = new Vector3(),
            angle;

        return function rotateCamera() {

            moveDirection.set( _moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0 );
            angle = moveDirection.length();

            if ( angle ) {

                _eye.copy( _this.object.position ).sub( _this.target );

                eyeDirection.copy( _eye ).normalize();
                objectUpDirection.copy( _this.object.up ).normalize();
                objectSidewaysDirection.crossVectors( objectUpDirection, eyeDirection ).normalize();

                objectUpDirection.setLength( _moveCurr.y - _movePrev.y );
                objectSidewaysDirection.setLength( _moveCurr.x - _movePrev.x );

                moveDirection.copy( objectUpDirection.add( objectSidewaysDirection ) );

                axis.crossVectors( moveDirection, _eye ).normalize();

                angle *= _this.rotateSpeed;
                quaternion.setFromAxisAngle( axis, angle );

                _eye.applyQuaternion( quaternion );
                _this.object.up.applyQuaternion( quaternion );

                _lastAxis.copy( axis );
                _lastAngle = angle;

            } else if ( ! _this.staticMoving && _lastAngle ) {

                _lastAngle *= Math.sqrt( 1.0 - _this.dynamicDampingFactor );
                _eye.copy( _this.object.position ).sub( _this.target );
                quaternion.setFromAxisAngle( _lastAxis, _lastAngle );
                _eye.applyQuaternion( quaternion );
                _this.object.up.applyQuaternion( quaternion );

            }

            _movePrev.copy( _moveCurr );

        };

    }() );


    this.zoomCamera = function () {

        var factor;

        if ( _state === STATE.TOUCH_ZOOM_PAN ) {

            factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
            _touchZoomDistanceStart = _touchZoomDistanceEnd;
            _eye.multiplyScalar( factor );

        } else {

            factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;

            if ( factor !== 1.0 && factor > 0.0 ) {

                _eye.multiplyScalar( factor );

            }

            if ( _this.staticMoving ) {

                _zoomStart.copy( _zoomEnd );

            } else {

                _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;

            }

        }

    };

    this.panCamera = ( function () {

        var mouseChange = new Vector2(),
            objectUp = new Vector3(),
            pan = new Vector3();

        return function panCamera() {

            mouseChange.copy( _panEnd ).sub( _panStart );

            if ( mouseChange.lengthSq() ) {

                mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );

                pan.copy( _eye ).cross( _this.object.up ).setLength( mouseChange.x );
                pan.add( objectUp.copy( _this.object.up ).setLength( mouseChange.y ) );

                _this.object.position.add( pan );
                _this.target.add( pan );

                if ( _this.staticMoving ) {

                    _panStart.copy( _panEnd );

                } else {

                    _panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );

                }

            }

        };

    }() );

    this.checkDistances = function () {

        if ( ! _this.noZoom || ! _this.noPan ) {

            if ( _eye.lengthSq() > _this.maxDistance * _this.maxDistance ) {

                _this.object.position.addVectors( _this.target, _eye.setLength( _this.maxDistance ) );
                _zoomStart.copy( _zoomEnd );

            }

            if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {

                _this.object.position.addVectors( _this.target, _eye.setLength( _this.minDistance ) );
                _zoomStart.copy( _zoomEnd );

            }

        }

    };

    this.update = function () {

        _eye.subVectors( _this.object.position, _this.target );

        if ( ! _this.noRotate ) {

            _this.rotateCamera();

        }

        if ( ! _this.noZoom ) {

            _this.zoomCamera();

        }

        if ( ! _this.noPan ) {

            _this.panCamera();

        }

        _this.object.position.addVectors( _this.target, _eye );

        _this.checkDistances();

        _this.object.lookAt( _this.target );

        if ( lastPosition.distanceToSquared( _this.object.position ) > EPS ) {

            _this.dispatchEvent( changeEvent );

            lastPosition.copy( _this.object.position );

        }

    };

    this.reset = function () {

        _state = STATE.NONE;
        _keyState = STATE.NONE;

        _this.target.copy( _this.target0 );
        _this.object.position.copy( _this.position0 );
        _this.object.up.copy( _this.up0 );

        _eye.subVectors( _this.object.position, _this.target );

        _this.object.lookAt( _this.target );

        _this.dispatchEvent( changeEvent );

        lastPosition.copy( _this.object.position );

    };

    // listeners

    function keydown( event ) {

        if ( _this.enabled === false ) return;

        window.removeEventListener( 'keydown', keydown );

        if ( _keyState !== STATE.NONE ) {

            return;

        } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && ! _this.noRotate ) {

            _keyState = STATE.ROTATE;

        } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && ! _this.noZoom ) {

            _keyState = STATE.ZOOM;

        } else if ( event.keyCode === _this.keys[ STATE.PAN ] && ! _this.noPan ) {

            _keyState = STATE.PAN;

        }

    }

    function keyup() {

        if ( _this.enabled === false ) return;

        _keyState = STATE.NONE;

        window.addEventListener( 'keydown', keydown, false );

    }

    function mousedown( event ) {

        if ( _this.enabled === false ) return;

        event.preventDefault();
        event.stopPropagation();

        if ( _state === STATE.NONE ) {

            switch ( event.button ) {
                case _this.mouseButtons.LEFT:{     //鼠标左键按下
                    _state=STATE.SELECTION;
                    break;
                }

                case _this.mouseButtons.MIDDLE_DOWN: { //这个其实是中间的滚轮按下的事件
                    _state = STATE.ROTATE;
                    break;
                }
                case _this.mouseButtons.MIDDLE: { //这个不知道怎么触发
                    _state = STATE.ZOOM;
                    break;
                }
                case _this.mouseButtons.RIGHT: { //这个是右键
                    _state = STATE.PAN;
                    break;
                }
                default:                         //左键直接到了这里
                    _state = STATE.NONE;

            }

        }

        var state = ( _keyState !== STATE.NONE ) ? _keyState : _state;

        //对应的是中键的按下
        if ( state === STATE.ROTATE && ! _this.noRotate ) {
            _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
            _movePrev.copy( _moveCurr );

        }
        else if ( state === STATE.ZOOM && ! _this.noZoom ) {
            _zoomStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
            _zoomEnd.copy( _zoomStart );
        }
        //右键的按下
        else if ( state === STATE.PAN && ! _this.noPan ) {
            _panStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
            _panEnd.copy( _panStart );

            start_time=(new Date()).getTime();          //记录右键按下的时间
        }
        else if(state === STATE.SELECTION && !_this.noSelection){
            //这里添加在渲染区域中左键点击之后发生的事情
            button_left_isDown = true;
            //创建一个div元素
            var selection_box = document.createElement('div');
            var e = event || window.event;
            pageX  = e.pageX;               //获取鼠标的x的坐标
            pageY = e.pageY;                //获取鼠标的y的坐标
            selection_box.id = 'box';     //之前创建的canvas的id=box
            selection_box.style.display = 'none';
            selection_box.style.left = pageX + 'px';
            selection_box.style.top = pageY + 'px';
            obj.appendChild(selection_box);    //body中添加box
        }

        document.addEventListener( 'mousemove', mousemove, false );
        document.addEventListener( 'mouseup', mouseup, false );

        _this.dispatchEvent( startEvent );

    }

    function mousemove( event ) {

        if ( _this.enabled === false ) return;

        event.preventDefault();
        event.stopPropagation();

        var state = ( _keyState !== STATE.NONE ) ? _keyState : _state;

        if ( state === STATE.ROTATE && ! _this.noRotate ) {

            _movePrev.copy( _moveCurr );
            _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );

        }
        else if ( state === STATE.ZOOM && ! _this.noZoom ) {

            _zoomEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );

        }
        else if ( state === STATE.PAN && ! _this.noPan ) {

            _panEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );

        }
        else if(state===STATE.SELECTION && !_this.noSelection){
            //鼠标左键拖动的时候
            if (button_left_isDown) {               //按下且移动，这就是我们需要的步骤
                var pagex = event.pageX;            //鼠标移动后的x的位置
                var pagey = event.pageY;            //鼠标移动后的y的位置
                var width = pagex - pageX;
                var height = pagey - pageY;

                //接下来应该有4种情况
                //当x变大的时候
                if (width > 0) {
                    //设置往右框选的时候的框的颜色
                    $('#box').style.background= "#0b93ff";    //设置背景颜色
                    $('#box').style.border = "1px solid #1028ff";  //设置边框颜色

                    $('#box').style.width = width + 'px';
                    $('#box').style.left = pageX + 'px';
                    $('#box').style.top = pageY + 'px';
                    //x变大而且变大，此时为右下角
                    if(height>0) {
                        $('#box').style.height = height + 'px';
                        $('#box').style.display = 'block';
                    }
                    //x变大但是y变小，此时为右上角
                    else{
                        $('#box').style.top = pagey + 'px';
                        $('#box').style.height = (-height) + 'px';
                        $('#box').style.display = 'block';
                    }
                }
                //当x不变或者变小的时候
                //当x变小的时候，应该以最后的鼠标的位置为绘制的起点
                else{
                    //当框选方向往左的时候，框的颜色发生变化
                    $('#box').style.background= "#ffa3fb";    //设置背景颜色
                    $('#box').style.border = "1px solid #ff40e9";  //设置边框颜色

                    $('#box').style.top = pageY + 'px';
                    $('#box').style.left = pagex + 'px';
                    $('#box').style.width = (-width) + 'px';
                    //左上角
                    if(height<0) {
                        $('#box').style.top = pagey + 'px';
                        $('#box').style.height = (-height) + 'px';
                        $('#box').style.display = 'block';
                    }
                    //左下角
                    else{
                        $('#box').style.height = height + 'px';
                        $('#box').style.display = 'block';
                    }
                }
            }
        }
    }

    function mouseup( event ) {
        end_time=(new Date()).getTime();
        if((end_time-start_time<=150)&&start_time!==0){ //如果右键的按下和松起在一秒钟之内，就显示鼠标右键下拉菜单
            //工作区右边菜单**********************************************************
            if(is_right_menu_exist){             //如果之前有右键菜单的时候，就先删除他
                document.getElementById('msg_menu').remove();
            }
            var msg = new Array();
            msg[0] = event.pageX;             //参数数组的两个为事件坐标
            msg[1] = event.pageY;
            msg[2] = '工作区';
            msg[3] = '右侧工作区';
            msg[4] = true;
            msg[5] = "?";
            msg[6] = "?";
            menu_of_right_button(msg);
            //工作区右边菜单**********************************************************
            //显示完成之后将两个事件归零
            start_time=0;
            end_time=0;
        }

        if(button_left_isDown) {
            var box = $('#box');
            pageX = 0;
            pageY = 0;
            button_left_isDown = false;
            obj.removeChild(box);  //删除box
        }

        if ( _this.enabled === false ) return;

        event.preventDefault();
        event.stopPropagation();

        _state = STATE.NONE;

        document.removeEventListener( 'mousemove', mousemove );
        document.removeEventListener( 'mouseup', mouseup );
        _this.dispatchEvent( endEvent );

    }

    function mousewheel( event ) {

        if ( _this.enabled === false ) return;

        if ( _this.noZoom === true ) return;

        event.preventDefault();
        event.stopPropagation();

        switch ( event.deltaMode ) {

            case 2:
                // Zoom in pages
                _zoomStart.y -= event.deltaY * 0.025;
                break;

            case 1:
                // Zoom in lines
                _zoomStart.y -= event.deltaY * 0.01;
                break;

            default:
                // undefined, 0, assume pixels
                _zoomStart.y -= event.deltaY * 0.00025;
                break;

        }

        _this.dispatchEvent( startEvent );
        _this.dispatchEvent( endEvent );

    }

    function touchstart( event ) {

        if ( _this.enabled === false ) return;

        event.preventDefault();

        switch ( event.touches.length ) {

            case 1:
                _state = STATE.TOUCH_ROTATE;
                _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
                _movePrev.copy( _moveCurr );
                break;

            default: // 2 or more
                _state = STATE.TOUCH_ZOOM_PAN;
                var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
                var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
                _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );

                var x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2;
                var y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2;
                _panStart.copy( getMouseOnScreen( x, y ) );
                _panEnd.copy( _panStart );
                break;

        }

        _this.dispatchEvent( startEvent );

    }

    function touchmove( event ) {

        if ( _this.enabled === false ) return;

        event.preventDefault();
        event.stopPropagation();

        switch ( event.touches.length ) {

            case 1:
                _movePrev.copy( _moveCurr );
                _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
                break;

            default: // 2 or more
                var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
                var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
                _touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy );

                var x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2;
                var y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2;
                _panEnd.copy( getMouseOnScreen( x, y ) );
                break;

        }

    }

    function touchend( event ) {

        if ( _this.enabled === false ) return;

        switch ( event.touches.length ) {

            case 0:
                _state = STATE.NONE;
                break;

            case 1:
                _state = STATE.TOUCH_ROTATE;
                _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
                _movePrev.copy( _moveCurr );
                break;

        }

        _this.dispatchEvent( endEvent );

    }

    function contextmenu( event ) {

        if ( _this.enabled === false ) return;

        event.preventDefault();

    }


    this.dispose = function () {

        this.domElement.removeEventListener( 'contextmenu', contextmenu, false );
        this.domElement.removeEventListener( 'mousedown', mousedown, false );
        this.domElement.removeEventListener( 'wheel', mousewheel, false );

        this.domElement.removeEventListener( 'touchstart', touchstart, false );
        this.domElement.removeEventListener( 'touchend', touchend, false );
        this.domElement.removeEventListener( 'touchmove', touchmove, false );

        document.removeEventListener( 'mousemove', mousemove, false );
        document.removeEventListener( 'mouseup', mouseup, false );

        window.removeEventListener( 'keydown', keydown, false );
        window.removeEventListener( 'keyup', keyup, false );

    };

    this.domElement.addEventListener( 'contextmenu', contextmenu, false );
    this.domElement.addEventListener( 'mousedown', mousedown, false );
    this.domElement.addEventListener( 'wheel', mousewheel, false );

    this.domElement.addEventListener( 'touchstart', touchstart, false );
    this.domElement.addEventListener( 'touchend', touchend, false );
    this.domElement.addEventListener( 'touchmove', touchmove, false );

    window.addEventListener( 'keydown', keydown, false );
    window.addEventListener( 'keyup', keyup, false );

    this.handleResize();

    // force an update at start
    this.update();

};

TrackballControls.prototype = Object.create( EventDispatcher.prototype );
TrackballControls.prototype.constructor = TrackballControls;

export { TrackballControls };
